/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * fastDogAdd.java
 *
 * Created on Mar 31, 2009, 10:50:41 PM
 */

package GUI.other;

import GUI.MainFrame;
import GUI.UserCard;
import functions.Breeds;
import functions.Dogs;
import functions.Dogy;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.sql.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import model.Breed;
import model.Dog;
import model.User;
import stuff.FDate;
import stuff.FormException;

/**
 *
 * @author JArik
 */
public class fastDogAdd extends javax.swing.JFrame implements fastAddInterface {

    /** Creates new form fastDogAdd */
    private MainFrame mainFrame;
    private ArrayList<Dog> dogs;
    private UserCard card;
    private User user;
    private ArrayList<Integer> deletedDogs;
    private JTextField activeField;
    private String addNewText, addNewDogText, newDogText;
    private Breed choosenBreed;
    public fastDogAdd(MainFrame mf, User usr, UserCard c) throws SQLException {
        initComponents();
        mainFrame = mf;
        dogs = usr.getDogs();
        user = usr;
        card = c;
        deletedDogs = new ArrayList<Integer>();

        boxPopup.add(boxList);
        Dimension dim = list.getSize();
        dim.width+=15;
        list.setMinimumSize(dim);

        addNewText = "<html><b>Добавить Новое</b>";
        newDogText = "Новое";
        addNewDogText = "Добавить";
        addDog.setText(addNewDogText);
        Dogy.placeToCenter(this);
        fillDogsTable();
    }
    private void fillDogsTable()
    {
        DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();
        for(int i=0; i< dogs.size(); i++)
        {
            model.addRow(new Object[]{dogs.get(i),
                                      dogs.get(i).getBirthDate(),
                                      dogs.get(i).getDeathDate(),
                                      dogs.get(i).getAge()});
        }
        dogsTable.setModel(model);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        boxPopup = new javax.swing.JPopupMenu();
        boxList = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        dialog = new javax.swing.JDialog();
        deathDatePanel = new javax.swing.JPanel();
        dogDeathDate = new javax.swing.JFormattedTextField();
        jLabel17 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        closeButton = new javax.swing.JButton();
        confirmButton = new javax.swing.JButton();
        addDogPanel = new javax.swing.JPanel();
        addDog = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        nickField = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        breedField = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        dogAgeField = new javax.swing.JFormattedTextField();
        jLabel13 = new javax.swing.JLabel();
        dogAgeDate = new javax.swing.JFormattedTextField();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        changeDog = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        dogsTable = new javax.swing.JTable();
        deleteDogButton = new javax.swing.JButton();
        deathHolder = new javax.swing.JPanel();
        deathCheckPanel = new javax.swing.JPanel();
        isDeadField = new javax.swing.JCheckBox();

        boxPopup.setAutoscrolls(true);
        boxPopup.setMaximumSize(new java.awt.Dimension(290, 645555));
        boxPopup.setPreferredSize(new java.awt.Dimension(190, 120));

        boxList.setAutoscrolls(true);
        boxList.setMaximumSize(new java.awt.Dimension(290, 32767));
        boxList.setMinimumSize(new java.awt.Dimension(120, 23));

        list.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Добавить новое" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        list.setMaximumSize(new java.awt.Dimension(290, 16));
        list.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listMouseClicked(evt);
            }
        });
        boxList.setViewportView(list);

        dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        dialog.setAlwaysOnTop(true);
        dialog.setResizable(false);
        dialog.setUndecorated(true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                dialogWindowClosed(evt);
            }
        });

        javax.swing.GroupLayout dialogLayout = new javax.swing.GroupLayout(dialog.getContentPane());
        dialog.getContentPane().setLayout(dialogLayout);
        dialogLayout.setHorizontalGroup(
            dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        dialogLayout.setVerticalGroup(
            dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        deathDatePanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        dogDeathDate.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        dogDeathDate.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dogDeathDateFocusLost(evt);
            }
        });
        dogDeathDate.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                dogDeathDateKeyReleased(evt);
            }
        });
        deathDatePanel.add(dogDeathDate, new org.netbeans.lib.awtextra.AbsoluteConstraints(105, 10, 76, -1));

        jLabel17.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel17.setText("ДД.ММ.ГГГГ");
        deathDatePanel.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(185, 10, -1, -1));

        jLabel16.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel16.setText("День смерти: ");
        deathDatePanel.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 10, -1, -1));

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        closeButton.setFont(new java.awt.Font("Tahoma", 1, 14));
        closeButton.setText("Закрыть");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        confirmButton.setFont(new java.awt.Font("Tahoma", 1, 14));
        confirmButton.setText("Подтвердить");
        confirmButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmButtonActionPerformed(evt);
            }
        });

        addDogPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Животные клиента", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 0, 0))); // NOI18N

        addDog.setFont(new java.awt.Font("Tahoma", 1, 12));
        addDog.setText("Новое");
        addDog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addDogActionPerformed(evt);
            }
        });

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel10.setText("Кличка: ");

        nickField.setFont(new java.awt.Font("Tahoma", 0, 12));

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel11.setText("Порода: ");

        breedField.setFont(new java.awt.Font("Tahoma", 0, 12));
        breedField.setName("breedField"); // NOI18N
        breedField.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                breedFieldMouseClicked(evt);
            }
        });
        breedField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                breedFieldActionPerformed(evt);
            }
        });
        breedField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                breedFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                breedFieldFocusLost(evt);
            }
        });
        breedField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                breedFieldKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                breedFieldKeyReleased(evt);
            }
        });

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel12.setText("Возраст: ");

        dogAgeField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#.##"))));
        dogAgeField.setToolTipText("Лет.месяцев(5.2) 5 лет, 2 месяца");
        dogAgeField.setFont(new java.awt.Font("Tahoma", 0, 12));
        dogAgeField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                dogAgeFieldKeyReleased(evt);
            }
        });

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel13.setText("День рождения: ");

        dogAgeDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd.MM.yyyy"))));
        dogAgeDate.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        dogAgeDate.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dogAgeDateFocusLost(evt);
            }
        });
        dogAgeDate.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                dogAgeDateKeyReleased(evt);
            }
        });

        jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel14.setText("Лет.месяцев");

        jLabel15.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel15.setText("ДД.ММ.ГГГГ");

        changeDog.setFont(new java.awt.Font("Tahoma", 1, 12));
        changeDog.setText("Изменить");
        changeDog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeDogActionPerformed(evt);
            }
        });

        jScrollPane2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));

        dogsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Имя/Порода", "Д.Р.", "Д.С.", "Возраст"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        dogsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                dogsTableMouseReleased(evt);
            }
        });
        dogsTable.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
                dogsTableCaretPositionChanged(evt);
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
            }
        });
        dogsTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                dogsTableKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(dogsTable);

        deleteDogButton.setFont(new java.awt.Font("Tahoma", 1, 12));
        deleteDogButton.setText("Удалить");
        deleteDogButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteDogButtonActionPerformed(evt);
            }
        });

        deathHolder.setLayout(new java.awt.BorderLayout());

        isDeadField.setFont(new java.awt.Font("Tahoma", 0, 12));
        isDeadField.setText("Животное умерло");
        isDeadField.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                isDeadFieldItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout deathCheckPanelLayout = new javax.swing.GroupLayout(deathCheckPanel);
        deathCheckPanel.setLayout(deathCheckPanelLayout);
        deathCheckPanelLayout.setHorizontalGroup(
            deathCheckPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(deathCheckPanelLayout.createSequentialGroup()
                .addComponent(isDeadField)
                .addContainerGap(181, Short.MAX_VALUE))
        );
        deathCheckPanelLayout.setVerticalGroup(
            deathCheckPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(deathCheckPanelLayout.createSequentialGroup()
                .addComponent(isDeadField)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        deathHolder.add(deathCheckPanel, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout addDogPanelLayout = new javax.swing.GroupLayout(addDogPanel);
        addDogPanel.setLayout(addDogPanelLayout);
        addDogPanelLayout.setHorizontalGroup(
            addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(addDogPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(addDogPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(addDogPanelLayout.createSequentialGroup()
                        .addComponent(deathHolder, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(addDogPanelLayout.createSequentialGroup()
                        .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel13)
                            .addComponent(jLabel12)
                            .addComponent(jLabel11)
                            .addComponent(jLabel10))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(breedField, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                            .addComponent(nickField)
                            .addGroup(addDogPanelLayout.createSequentialGroup()
                                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(dogAgeField)
                                    .addComponent(dogAgeDate, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel14)
                                    .addComponent(jLabel15))
                                .addGap(57, 57, 57))))
                    .addGroup(addDogPanelLayout.createSequentialGroup()
                        .addComponent(deleteDogButton)
                        .addGap(27, 27, 27)
                        .addComponent(changeDog)
                        .addGap(18, 18, 18)
                        .addComponent(addDog, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        addDogPanelLayout.setVerticalGroup(
            addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addDogPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(nickField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(breedField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(dogAgeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(dogAgeDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel15))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deathHolder, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(addDogPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(deleteDogButton)
                    .addComponent(addDog)
                    .addComponent(changeDog))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addDogPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(closeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 124, Short.MAX_VALUE)
                        .addComponent(confirmButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addDogPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmButton)
                    .addComponent(closeButton)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        try
        {
          if(deletedDogs.size() > 0)
          {
             Dogs.unDelete(deletedDogs);
          }
        } catch(SQLException e)
        {
            mainFrame.SQLException(e);
        }
        this.dispose();
}//GEN-LAST:event_closeButtonActionPerformed

    private void addDogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addDogActionPerformed

        if(addDog.getText().equals(addNewDogText))
            addDog();
        else
        if(addDog.getText().equals(newDogText))
        {
           clearFields();
           nickField.requestFocus();
           dogsTable.clearSelection();
           addDog.setText(addNewDogText);
        }
        
}//GEN-LAST:event_addDogActionPerformed

    private void addDog()
    {
        DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();
        try {
            if (nickField.getText().isEmpty() && breedField.getText().isEmpty()) {
                throw new FormException("Введите кличку или породу животного.");
            }
            SimpleDateFormat form = new SimpleDateFormat("dd.MM.yyyy");
            FDate date = null, dDate = null;
            
            if(!dogAgeDate.getText().isEmpty())
              date  = new FDate(form.parse(dogAgeDate.getText()).getTime());

            if(!dogDeathDate.getText().isEmpty())
               dDate  = new FDate(form.parse(dogDeathDate.getText()).getTime());

            Dog dg= new Dog(0,date,user.getId(),
                                     breedField.getText() == null ? "":breedField.getText(),
                                     nickField.getText()== null ? "":nickField.getText() );

            dg.setDeathDate(dDate);
            model.addRow(
                    new Object[]{dg,
                                 date,
                                 dg.getDeathDate(),
                                 dg.getAge()}
                        );
            dogsTable.setModel(model);
            clearFields();
        } catch (FormException fe) {
            mainFrame.FormException(this, fe.getMessage());
        }catch(Exception e) {
            mainFrame.Exception(e);
        }
    }
    private void dogAgeFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dogAgeFieldKeyReleased
        String age = dogAgeField.getText();
        String[] test = age.split("\\.");
        int month = 0;
        int year = 0;
        if (!age.isEmpty()) {
            if (age.contains(".")) {
                if (age.split("\\.").length >= 1) {
                    if (!age.split("\\.")[0].isEmpty()) {
                        year = Integer.parseInt(age.split("\\.")[0]);
                    } else {
                        year = 0;
                    }
                    if (age.split("\\.").length >= 2) {
                        month = Integer.parseInt(age.split("\\.")[1]);
                    }
                }
            } else {
                year = Integer.parseInt(age);
            }

            SimpleDateFormat form = new SimpleDateFormat("dd.MM.yyyy");
            Calendar vozrast = Calendar.getInstance();
            vozrast.setTime(Calendar.getInstance().getTime());
            vozrast.add(Calendar.YEAR, -year);
            vozrast.add(Calendar.MONTH, -month);
            age = form.format(vozrast.getTime());
            dogAgeDate.setText(age);
        }
}//GEN-LAST:event_dogAgeFieldKeyReleased

    private void changeDogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeDogActionPerformed
        if(dogsTable.getSelectedRow() >= 0) {
            DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();

            //dogAgeFieldKeyReleased(null);
            try
            {
                Dog dg = (Dog)model.getValueAt(dogsTable.getSelectedRow(), 0);
                if (nickField.getText().isEmpty() && breedField.getText().isEmpty()) {
                    throw new FormException("Введите кличку или породу животного.");
                }
                SimpleDateFormat form = new SimpleDateFormat("dd.MM.yyyy");
                FDate date = null, dDate = null;
                try
                {
                if(!dogAgeDate.getText().isEmpty())
                  date  = new FDate(form.parse(dogAgeDate.getText()).getTime());
                }catch(Exception e)
                {
                    date = null;
                }
                
                try
                {
                if(!dogDeathDate.getText().isEmpty())
                  dDate  = new FDate(form.parse(dogDeathDate.getText()).getTime());
                }catch(Exception e)
                {
                    dDate = null;
                }

                dg= new Dog(dg.getId(),
                                date,
                                user.getId(),
                                breedField.getText() == null ? "":breedField.getText(),
                                nickField.getText()== null ? "":nickField.getText() );
                dg.setDeathDate(dDate);
                model.setValueAt(dg, dogsTable.getSelectedRow(), 0);
                //birthDate
                if(dg.getBirthDate() != null )
                {
                  model.setValueAt(dg.getBirthDate(), dogsTable.getSelectedRow(), 1);
                  model.setValueAt(dg.getDeathDate(), dogsTable.getSelectedRow(), 2);
                  model.setValueAt(dg.getAge(), dogsTable.getSelectedRow(), 3);
                  dogAgeField.setText(dg.getAge());
                }
                clearFields();
            }catch(Exception e)
            {
                mainFrame.FormException(this, e.getMessage());
            }
        }else
            mainFrame.FormException(this, "Выделите животное для изменения");
}//GEN-LAST:event_changeDogActionPerformed

    private void dogsTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dogsTableMouseReleased
        dogsTableItemSelected();
}//GEN-LAST:event_dogsTableMouseReleased

    private void dogsTableCaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_dogsTableCaretPositionChanged

}//GEN-LAST:event_dogsTableCaretPositionChanged

    private void dogsTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dogsTableKeyReleased
        dogsTableItemSelected();
}//GEN-LAST:event_dogsTableKeyReleased

    private void deleteDogButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteDogButtonActionPerformed
        if(dogsTable.getSelectedRow() >= 0) {
            DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();
            Dog dg = (Dog)model.getValueAt(dogsTable.getSelectedRow(), 0);
            try{
                if(dg.getId() != 0)
                {
                  Dogs.deleteDog(dg.getId());
                  deletedDogs.add(dg.getId());
                }
                model.removeRow(dogsTable.getSelectedRow());
                dogsTable.setModel(model);
                clearFields();
            } catch(SQLException ex) {
                mainFrame.SQLException(ex);
            }
        }else
            mainFrame.FormException(this,
                    "Выделите животное которое хотите удалить.");
    }//GEN-LAST:event_deleteDogButtonActionPerformed

    private void confirmButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmButtonActionPerformed
        DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();
        if(mainFrame.confirmForm(this, "Подтвердить изменения?"))
        {
             try
            {
                 user.setDog(null);
                for(int i=0; i< model.getRowCount(); i++)
                {

                      Dog dg = (Dog)model.getValueAt(i, 0);
                      if(dg.getId() != 0)
                      {
                          Dogs.changeDog(dg.getId(), user.getId(),
                                  dg.getNick() == null ? "":dg.getNick(),
                                  dg.getBreed() == null ? "":dg.getBreed(),
                                  dg.getBirthDate(),
                                  dg.getDeathDate()
                                  );
                      }
                      else
                      {
                          int id = Dogs.addDog(user.getId(),
                                  dg.getNick() == null ? "":dg.getNick(),
                                  dg.getBreed() == null ? "":dg.getBreed(),
                                  dg.getBirthDate());
                          dg.setId(id);
                          model.setValueAt(dg, i, 0);
                      }
                      user.setDog(dg);
                }
          card.fillDogTable(user.getDogs());
          dogsTable.setModel(model);
          this.dispose();
          } catch(SQLException e)
            {
                mainFrame.SQLException(e);
            }
        }
    }//GEN-LAST:event_confirmButtonActionPerformed

    private void dogAgeDateKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dogAgeDateKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_dogAgeDateKeyReleased

    private void dogAgeDateFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dogAgeDateFocusLost
        
    }//GEN-LAST:event_dogAgeDateFocusLost

    private void listMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMouseClicked
        boxPopup.setVisible(false);
        if ( list.getSelectedValue() != null &&
                list.getSelectedValue().toString().equals(addNewText) ||
                list.getSelectedIndex() == -1) {
            showAddWindow();
        } else {
            if(activeField != null) {
                JTextField field = activeField;
                field.setText(list.getSelectedValue().toString());

                if(activeField.getName().equals("breedField"))
                    choosenBreed = (Breed)list.getSelectedValue();

            }
        }
    }//GEN-LAST:event_listMouseClicked

    private void dialogWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_dialogWindowClosed
        this.setEnabled(true);
        this.requestFocus();
}//GEN-LAST:event_dialogWindowClosed

    private void breedFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_breedFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_breedFieldActionPerformed

    private void breedFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_breedFieldFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_breedFieldFocusGained

    private void breedFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_breedFieldFocusLost
        boxPopup.setVisible(false);
        //Dogy.focusLost(breedField, distText);
    }//GEN-LAST:event_breedFieldFocusLost

    private void breedFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_breedFieldKeyPressed
        Dogy.listScroll(list, evt);
    }//GEN-LAST:event_breedFieldKeyPressed

    private void breedFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_breedFieldKeyReleased
        activeField = breedField;
        if( evt != null && evt.getKeyCode() == KeyEvent.VK_ENTER) {
            boxPopup.setVisible(false);
            breedField.nextFocus();
            if(!breedField.getText().equals("") || list.getSelectedIndex() >0)
               listMouseClicked(null);
            else
                showAddWindow();

        } else if(evt != null && evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            boxPopup.setVisible(false);
        }
        else if(!dialog.isVisible() && (evt == null || !evt.isActionKey()) ){
            try {
                list.ensureIndexIsVisible(0);
                ArrayList choices=null;
                
                choices= Breeds.getByName(breedField.getText());
                

                choices.add(0,addNewText);

                list.setListData(choices.toArray());

                boxPopup.setLocation(breedField.getLocationOnScreen().x,
                        breedField.getLocationOnScreen().y + breedField.getHeight());
                boxPopup.setVisible(true);

            } catch (SQLException ex) {
                mainFrame.SQLException(ex);
            }
        }
    }//GEN-LAST:event_breedFieldKeyReleased

    private void breedFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_breedFieldMouseClicked
        activeField = breedField;
        if(breedField.getText().equals(""))
            breedFieldKeyReleased(null);
    }//GEN-LAST:event_breedFieldMouseClicked

    private void isDeadFieldItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_isDeadFieldItemStateChanged
        if(isDeadField.isSelected())
        {
            deathHolder.removeAll();
            deathHolder.add(deathDatePanel );
            deathHolder.repaint();
            dogDeathDate.requestFocus();
            pack();
        }else
        {
            deathHolder.removeAll();
            deathHolder.add(deathCheckPanel );
            deathHolder.repaint();
            dogDeathDate.setText("");
            pack();
        }
}//GEN-LAST:event_isDeadFieldItemStateChanged

    private void dogDeathDateFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dogDeathDateFocusLost
        // TODO add your handling code here:
}//GEN-LAST:event_dogDeathDateFocusLost

    private void dogDeathDateKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dogDeathDateKeyReleased
        // TODO add your handling code here:
}//GEN-LAST:event_dogDeathDateKeyReleased
    private void dogsTableItemSelected()
    {
        if(dogsTable.getSelectedRow() >= 0 )
        {
          addDog.setText(newDogText);
          DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();
          Dog dg = (Dog)model.getValueAt(dogsTable.getSelectedRow(), 0);
          nickField.setText(dg.getNick());
          breedField.setText(dg.getBreed());
          dogAgeField.setText(dg.getAge()+"");
          SimpleDateFormat form = new SimpleDateFormat("dd.MM.yyyy");
          if(dg.getBirthDate() != null)
            dogAgeDate.setText(form.format(dg.getBirthDate()));
          else
            dogAgeDate.setText("");
          if(dg.isDead())
          {
              isDeadField.setSelected(true);
              dogDeathDate.setText(form.format(dg.getDeathDate()));
          }else
              isDeadField.setSelected(false);
        }else
        {
            clearFields();
        }
    }

    private void clearFields()
    {
        isDeadField.setSelected(false);
        nickField.setText("");
        breedField.setText("");
        dogAgeField.setText("");
        dogAgeDate.setText("");
        dogDeathDate.setText("");
    }

    private void showAddWindow()
    {
        if(activeField.getName().equals("breedField"))
              dialog.setContentPane(new fastBreedAdd(activeField.getText(),this));

        dialog.pack();
        dialog.setLocation(activeField.getLocationOnScreen().x,
               activeField.getLocationOnScreen().y + activeField.getHeight());
        dialog.setVisible(true);
    }

    public void setActiveFieldText(Object obj)
    {
      activeField.setText(obj.toString());
    }

    public void disposeDialog()
    {
        dialog.setVisible(false);
    }
    public String getActiveFieldText()
{
    return activeField.getText();
}
    /**
    * @param args the command line arguments
    */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addDog;
    private javax.swing.JPanel addDogPanel;
    private javax.swing.JScrollPane boxList;
    private javax.swing.JPopupMenu boxPopup;
    private javax.swing.JTextField breedField;
    private javax.swing.JButton changeDog;
    private javax.swing.JButton closeButton;
    private javax.swing.JButton confirmButton;
    private javax.swing.JPanel deathCheckPanel;
    private javax.swing.JPanel deathDatePanel;
    private javax.swing.JPanel deathHolder;
    private javax.swing.JButton deleteDogButton;
    private javax.swing.JDialog dialog;
    private javax.swing.JFormattedTextField dogAgeDate;
    private javax.swing.JFormattedTextField dogAgeField;
    private javax.swing.JFormattedTextField dogDeathDate;
    private javax.swing.JTable dogsTable;
    private javax.swing.JCheckBox isDeadField;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList list;
    private javax.swing.JTextField nickField;
    // End of variables declaration//GEN-END:variables


}
